/**
 * 项目服务类
 * 处理不同方案类型的项目数据相关操作
 */

const dataHelper = require('../../helpers/data_helper.js');
const dayjs = require('dayjs');
const cloudHelper = require('../../helpers/cloud_helper.js');

/**
 * 项目服务类
 */
class ProjectService {
  /**
   * 创建项目
   * @param {Object} projectData 项目数据
   * @returns {Object} 处理后的项目数据
   */
  static createProject(projectData) {
    // 复制项目数据
    const project = { ...projectData };
    
    // 设置基本时间字段
    const now = dayjs().valueOf();
    project.createTime = now;
    project.updateTime = now;
    
    // 设置默认状态
    if (!project.level1) {
      project.level1 = 1; // 项目默认状态：项目审核
      project.level2 = 'applied'; // 二级状态：已申请
      project.statusDesc = '等待项目审核';
    }
    
    return project;
  }
  
  /**
   * 根据项目类型获取项目表单配置
   * @param {String} type 项目类型
   * @returns {Object} 项目表单配置
   */
  static getProjectFormConfig(type) {
    // 基本表单配置（所有项目类型通用）
    const baseFormConfig = {
      sections: [{
        title: "基础信息",
        fields: [
          { name: "customerName", label: "客户名称", type: "input", required: true },
          { name: "name", label: "型号", type: "input", required: true },
          { name: "projectType", label: "项目类型", type: "select", required: true,
            options: ['磁编', '霍尔', '吸尘器', '风机', '水泵', '其他'] },
          { name: "startDate", label: "开始时间", type: "date", required: true },
          { name: "priority", label: "优先级", type: "priority", required: true,
            options: [
              { value: "low", label: "低" },
              { value: "normal", label: "中" },
              { value: "high", label: "高" }
            ] },
          { name: "deadline", label: "截止时间", type: "date", required: true },
          { name: "sampleCount", label: "样品需求量", type: "number" },
          { name: "hasSample", label: "有无样机", type: "select", 
            options: ['有', '无'] },
          { name: "description", label: "项目描述", type: "textarea" }
        ]
      }]
    };

    // 不同项目类型的特定表单配置
    const typeFormConfig = {
      '磁编': { // 磁编类型只有基础信息
        sections: [...baseFormConfig.sections]
      },
      
      '霍尔': { // 霍尔类型只有基础信息
        sections: [...baseFormConfig.sections]
      },
      
      '吸尘器': {
        sections: [
          ...baseFormConfig.sections,
          {
            title: "参数",
            groups: [
              {
                title: "基本参数",
                icon: "📋",
                fields: [
                  { name: "workTemp", label: "工作环境温度", type: "input", unit: "℃" },
                  { name: "certification", label: "认证要求", type: "input" },
                  { name: "conformalCoating", label: "三防漆要求", type: "select", options: ['有', '无'] },
                  
                  // 吸尘器特有参数
                  { name: "suctionPower", label: "吸力", type: "input", unit: "W" },
                  { name: "airVolume", label: "风量", type: "input", unit: "m³/min" },
                  { name: "dustCapacity", label: "尘桶容量", type: "input", unit: "L" },
                  { name: "filterType", label: "过滤系统", type: "input" },
                  { name: "noiseLevel", label: "噪音级别", type: "input", unit: "dB" },
                  
                  // 电机参数
                  { name: "lowPower", label: "低功耗", type: "input", unit: "uA" },
                  { name: "startupTime", label: "启动时间", type: "input", unit: "S" },
                  { name: "ratedVoltage", label: "额定电压", type: "input", unit: "V" },
                  { name: "maxPower", label: "最大功率", type: "input", unit: "W" },
                  { name: "maxSpeed", label: "最高转速", type: "input", unit: "RPM" }
                ]
              },
              {
                title: "控制",
                icon: "🎮",
                fields: [
                  { name: "controlMode", label: "控制模式", type: "select", 
                    options: ['开环控制', '闭环控制', 'PWM控制', '自适应控制'] },
                  { name: "controlAlgorithm", label: "控制算法", type: "select",
                    options: ['无', 'PID', '模糊控制', '神经网络'] }
                ]
              },
              {
                title: "保护",
                icon: "🛡️",
                fields: [
                  { name: "stallProtection", label: "堵转保护", type: "select", options: ['有', '无'] },
                  { name: "overvoltageProtection", label: "过压保护", type: "select", options: ['有', '无'] },
                  { name: "undervoltageProtection", label: "欠压保护", type: "select", options: ['有', '无'] },
                  { name: "temperatureProtection", label: "温度保护", type: "select", options: ['有', '无'] },
                  { name: "overcurrentProtection", label: "过流保护", type: "select", options: ['有', '无'] }
                ]
              }
            ]
          }
        ]
      },
      
      '风机': {
        sections: [
          ...baseFormConfig.sections,
          {
            title: "参数",
            groups: [
              {
                title: "基本参数",
                icon: "📋",
                fields: [
                  { name: "workTemp", label: "工作环境温度", type: "input", unit: "℃" },
                  { name: "certification", label: "认证要求", type: "input" },
                  { name: "conformalCoating", label: "三防漆要求", type: "select", options: ['有', '无'] },
                  
                  // 风机特有参数
                  { name: "airFlow", label: "风量", type: "input", unit: "m³/min" },
                  { name: "staticPressure", label: "静压", type: "input", unit: "Pa" },
                  { name: "fanType", label: "风扇类型", type: "input" },
                  { name: "bladeMaterial", label: "扇叶材质", type: "input" },
                  { name: "noiseLevel", label: "噪音级别", type: "input", unit: "dB" },
                  
                  // 电机参数
                  { name: "lowPower", label: "低功耗", type: "input", unit: "uA" },
                  { name: "startupTime", label: "启动时间", type: "input", unit: "S" },
                  { name: "ratedVoltage", label: "额定电压", type: "input", unit: "V" },
                  { name: "maxPower", label: "最大功率", type: "input", unit: "W" },
                  { name: "maxSpeed", label: "最高转速", type: "input", unit: "RPM" }
                ]
              },
              {
                title: "控制",
                icon: "🎮",
                fields: [
                  { name: "controlMode", label: "控制模式", type: "select", 
                    options: ['开环控制', '闭环控制', 'PWM控制', '自适应控制'] },
                  { name: "controlInterface", label: "控制接口", type: "select",
                    options: ['PWM', '模拟量', '串口', 'I2C'] },
                  { name: "speedControl", label: "调速方式", type: "select",
                    options: ['无级调速', '多级调速', '定速'] }
                ]
              },
              {
                title: "保护",
                icon: "🛡️",
                fields: [
                  { name: "stallProtection", label: "堵转保护", type: "select", options: ['有', '无'] },
                  { name: "overvoltageProtection", label: "过压保护", type: "select", options: ['有', '无'] },
                  { name: "undervoltageProtection", label: "欠压保护", type: "select", options: ['有', '无'] },
                  { name: "temperatureProtection", label: "温度保护", type: "select", options: ['有', '无'] }
                ]
              }
            ]
          }
        ]
      },
      
      '水泵': {
        sections: [
          ...baseFormConfig.sections,
          {
            title: "参数",
            groups: [
              {
                title: "基本参数",
                icon: "📋",
                fields: [
                  { name: "workTemp", label: "工作环境温度", type: "input", unit: "℃" },
                  { name: "certification", label: "认证要求", type: "input" },
                  { name: "conformalCoating", label: "三防漆要求", type: "select", options: ['有', '无'] },
                  { name: "waterproofLevel", label: "防水等级", type: "input" },
                  
                  // 水泵特有参数
                  { name: "flowRate", label: "流量", type: "input", unit: "L/min" },
                  { name: "maxHead", label: "最大扬程", type: "input", unit: "m" },
                  { name: "pumpType", label: "泵类型", type: "input" },
                  { name: "impellerType", label: "叶轮类型", type: "input" },
                  { name: "inlet", label: "进水口规格", type: "input" },
                  { name: "outlet", label: "出水口规格", type: "input" },
                  
                  // 电机参数
                  { name: "lowPower", label: "低功耗", type: "input", unit: "uA" },
                  { name: "startupTime", label: "启动时间", type: "input", unit: "S" },
                  { name: "ratedVoltage", label: "额定电压", type: "input", unit: "V" },
                  { name: "maxPower", label: "最大功率", type: "input", unit: "W" },
                  { name: "maxSpeed", label: "最高转速", type: "input", unit: "RPM" }
                ]
              },
              {
                title: "控制",
                icon: "🎮",
                fields: [
                  { name: "controlMode", label: "控制模式", type: "select", 
                    options: ['开环控制', '闭环控制', 'PWM控制', '自适应控制'] },
                  { name: "controlInterface", label: "控制接口", type: "select",
                    options: ['PWM', '模拟量', '串口', 'I2C'] }
                ]
              },
              {
                title: "保护",
                icon: "🛡️",
                fields: [
                  { name: "dryRunningProtection", label: "干运行保护", type: "select", options: ['有', '无'] },
                  { name: "overvoltageProtection", label: "过压保护", type: "select", options: ['有', '无'] },
                  { name: "undervoltageProtection", label: "欠压保护", type: "select", options: ['有', '无'] },
                  { name: "temperatureProtection", label: "温度保护", type: "select", options: ['有', '无'] },
                  { name: "overflowProtection", label: "溢水保护", type: "select", options: ['有', '无'] }
                ]
              }
            ]
          }
        ]
      },
      
      '其他': {
        sections: [
          ...baseFormConfig.sections,
          {
            title: "参数",
            groups: [
              {
                title: "基本参数",
                icon: "📋",
                fields: [
                  { name: "workTemp", label: "工作环境温度", type: "input", unit: "℃" },
                  { name: "certification", label: "认证要求", type: "input" },
                  { name: "conformalCoating", label: "三防漆要求", type: "select", options: ['有', '无'] },
                ]
              },
              {
                title: "自定义参数",
                icon: "🔧",
                fields: [
                  { name: "customParam1", label: "自定义参数1", type: "input" },
                  { name: "customParam2", label: "自定义参数2", type: "input" },
                  { name: "customParam3", label: "自定义参数3", type: "input" }
                ]
              }
            ]
          }
        ]
      },

      // 默认为电机控制类型，包含全部可能参数
      '电机控制': {
        sections: [
          ...baseFormConfig.sections,
          {
            title: "参数",
            groups: [
              {
                title: "基本参数",
                icon: "📋",
                fields: [
                  { name: "workTemp", label: "工作环境温度", type: "input", unit: "℃" },
                  { name: "certification", label: "认证要求", type: "input" },
                  { name: "lowPower", label: "低功耗", type: "input", unit: "uA" },
                  { name: "startupTime", label: "启动时间", type: "input", unit: "S" },
                  { name: "conformalCoating", label: "三防漆要求", type: "select", options: ['有', '无'] },
                  { name: "ratedVoltage", label: "额定电压", type: "input", unit: "V" },
                  { name: "maxPower", label: "最大功率", type: "input", unit: "W" },
                  { name: "maxSpeed", label: "最高转速", type: "input", unit: "RPM" },
                  { name: "polePairs", label: "极对数", type: "input" },
                  { name: "hasHall", label: "HALL/磁编", type: "select", options: ['有', '无'] },
                  { name: "hasFG", label: "FG", type: "select", options: ['有', '无'] }
                ]
              },
              {
                title: "控制",
                icon: "🎮",
                fields: [
                  { name: "controlMode", label: "控制模式", type: "select", 
                    options: ['开环控制', '闭环控制', 'PWM控制', '自适应控制'] },
                  { name: "controlAlgorithm", label: "控制算法", type: "select",
                    options: ['无', 'PID', '模糊控制', '神经网络'] },
                  { name: "rotation", label: "正反转", type: "select",
                    options: ['正转', '反转', '正反转'] },
                  { name: "hasBrake", label: "刹车功能", type: "select", options: ['有', '无'] }
                ]
              },
              {
                title: "保护",
                icon: "🛡️",
                fields: [
                  { name: "stallProtection", label: "堵转保护", type: "select", options: ['有', '无'] },
                  { name: "overvoltageProtection", label: "过压保护", type: "select", options: ['有', '无'] },
                  { name: "undervoltageProtection", label: "欠压保护", type: "select", options: ['有', '无'] },
                  { name: "temperatureProtection", label: "温度保护", type: "select", options: ['有', '无'] },
                  { name: "overcurrentProtection", label: "过流保护", type: "select", options: ['有', '无'] },
                  { name: "currentLimitProtection", label: "限流保护", type: "select", options: ['有', '无'] },
                  { name: "blockageProtection", label: "堵孔/空转保护", type: "select", options: ['有', '无'] },
                  { name: "phaseProtection", label: "缺相保护", type: "select", options: ['有', '无'] }
                ]
              }
            ]
          }
        ]
      }
    };

    // 返回对应项目类型的表单配置，如果未找到则返回默认配置
    return typeFormConfig[type] || typeFormConfig['电机控制'];
  }
  
  /**
   * 设置项目默认参数值
   * @param {String} type 项目类型
   * @returns {Object} 项目默认参数
   */
  static getProjectDefaultParams(type) {
    const defaultParams = {
      '霍尔': {
        workTemp: '0~70',
        certification: 'CE/UL',
        lowPower: '10',
        startupTime: '500',
        conformalCoating: '无',
        ratedVoltage: '5',
        maxPower: '0.1',
        maxSpeed: '10000',
        polePairs: '1',
        hasHall: '有',
        controlMode: '闭环控制',
        controlAlgorithm: 'PID',
        rotation: '正转',
        hasBrake: '无',
        hasFG: '有',
        stallProtection: '无',
        overvoltageProtection: '无',
        undervoltageProtection: '无',
        temperatureProtection: '无',
        overcurrentProtection: '无',
        currentLimitProtection: '无',
        blockageProtection: '无',
        phaseProtection: '无'
      },
      
      '磁编': {
        workTemp: '0~70',
        certification: 'CE/UL',
        lowPower: '无',
        startupTime: '500',
        conformalCoating: '无',
        ratedVoltage: '5',
        maxPower: '0.1',
        maxSpeed: '10000',
        polePairs: '1',
        hasHall: '无',
        controlMode: '开环控制',
        controlAlgorithm: '无',
        rotation: '正转',
        hasBrake: '无',
        hasFG: '无',
        stallProtection: '无',
        overvoltageProtection: '无',
        undervoltageProtection: '无',
        temperatureProtection: '无',
        overcurrentProtection: '无',
        currentLimitProtection: '无',
        blockageProtection: '无',
        phaseProtection: '无'
      },
      
      '吸尘器': {
        workTemp: '-10~50',
        certification: 'CE/UL',
        lowPower: '50',
        startupTime: '2000',
        conformalCoating: '有',
        suctionPower: '400',
        airVolume: '1.2',
        dustCapacity: '0.5',
        filterType: 'HEPA',
        noiseLevel: '65',
        ratedVoltage: '12',
        maxPower: '450',
        maxSpeed: '22000',
        controlMode: 'PWM控制',
        controlAlgorithm: 'PID',
        stallProtection: '有',
        overvoltageProtection: '有',
        undervoltageProtection: '有',
        temperatureProtection: '有',
        overcurrentProtection: '有'
      },
      
      '风机': {
        workTemp: '-20~60',
        certification: 'CE/UL',
        conformalCoating: '无',
        airFlow: '120',
        staticPressure: '250',
        fanType: '离心风机',
        bladeMaterial: '塑料',
        noiseLevel: '45',
        lowPower: '100',
        startupTime: '1500',
        ratedVoltage: '24',
        maxPower: '60',
        maxSpeed: '4500',
        controlMode: 'PWM控制',
        controlInterface: 'PWM',
        speedControl: '无级调速',
        stallProtection: '有',
        overvoltageProtection: '有',
        undervoltageProtection: '有',
        temperatureProtection: '有'
      },
      
      '水泵': {
        workTemp: '0~40',
        certification: 'CE/UL',
        conformalCoating: '有',
        waterproofLevel: 'IPX8',
        flowRate: '5',
        maxHead: '6',
        pumpType: '离心泵',
        impellerType: '闭式',
        inlet: 'G1/2',
        outlet: 'G1/2',
        lowPower: '200',
        startupTime: '3000',
        ratedVoltage: '12',
        maxPower: '45',
        maxSpeed: '3000',
        controlMode: '闭环控制',
        controlInterface: 'PWM',
        dryRunningProtection: '有',
        overvoltageProtection: '有',
        undervoltageProtection: '有',
        temperatureProtection: '有',
        overflowProtection: '有'
      },
      
      '其他': {
        workTemp: '0~50',
        certification: '无',
        conformalCoating: '无'
      }
    };
    
    return defaultParams[type] || defaultParams['电机控制'];
  }
  
  /**
   * 远程创建项目
   * @param {Object} projectData 项目数据
   * @returns {Promise<Object>} 处理结果
   */
  static async createProjectRemote(projectData) {
    try {
      // 处理数据结构
      let processedData = this.createProject(projectData);
      
      // 确保数据中包含项目名称字段
      if (!processedData.projectTitle) {
        console.warn('[项目服务] 缺少项目名称字段，自动添加');
        processedData.projectTitle = '未命名项目';
        processedData.projectName = '未命名项目';
        processedData.name = '未命名项目';
      }
      
      // 调用云函数创建项目
      const result = await cloudHelper.callCloudData('research_project/create', processedData, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目服务] 远程创建项目失败:', e);
      throw e;
    }
  }
  
  /**
   * 获取项目详情
   * @param {String} projectId 项目ID
   * @returns {Promise<Object>} 项目详情
   */
  static async getProjectDetail(projectId) {
    try {
      const result = await cloudHelper.callCloudData('research_project/detail', {
        id: projectId
      });
      
      return result;
    } catch (e) {
      console.error('[项目服务] 获取项目详情失败:', e);
      throw e;
    }
  }
}

module.exports = ProjectService; 